<!--
 * @author wangjinqiu
 -->
<template>
  <div class="app-container courseware-container">
    <div v-if="state == 'u'" class="courseware-search merge">
      <span class="svg-container">
        <svg-icon icon-class="search" />
      </span>
      <el-input
        v-model="listQuery.name"
        placeholder="按课件名称搜索"
        class="search-input"
        @keyup.enter.native="handleFilter"
      />
      <div class="courseware-search-btn">
        <el-button type="primary" @click="handleFilter">{{ $t('table.search') }}</el-button>
        <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
      </div>
    </div>
    <div class="filter-container btn-container">
      <div class="btn-container-title">
        <span>课件资源</span>
        <el-button v-if="superId !== '-1'" type="text" style="margin-left: 10px;margin-bottom: 4px;" @click="goback">
          返回上一级
        </el-button>
      </div>
      <div class="btn-container-btns">
        <el-button v-if="state == 'c'" style="margin-left: 10px;" @click="handleSelects">选择课件</el-button>
        <el-button v-if="state == 'u' && $route.query.status != '0'" v-waves style="margin-left: 10px;" @click="handleDeletes">批量删除</el-button>
        <el-button style="margin-left: 10px;" @click="$router.go(-1)">返回</el-button>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-cell-style="rowClass"
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item :label="$t('table.courseware.name')">
              <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.courseware.remark')">
              <span>{{ props.row.remark }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.courseware.crtuser')">
              <span>{{ props.row.crtUser }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.courseware.comName')">
              <span>{{ props.row.comName ? props.row.comName : '平台' }}</span>
            </el-form-item>
            <el-form-item :label="$t('table.courseware.crttime')">
              <span>{{ props.row.crtTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" />
      <el-table-column :label="$t('table.courseware.name')" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="!scope.row.videoId" class="svg-container">
            <svg-icon icon-class="folder" />
          </span>
          <span v-if="!scope.row.videoId" class="link-type" @click="handleLevel(scope.row)">{{ scope.row.name }}</span>
          <span v-if="scope.row.videoId">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="state == 'c'" :label="$t('table.courseware.remark')" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="state == 'c'" :label="$t('table.courseware.comName')" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.comName ? scope.row.comName : '平台' }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="state == 'c'":label="$t('table.courseware.crtuser')" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.crtUser }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="state == 'c'" :label="$t('table.courseware.crttime')" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.crtTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="state == 'c'" :label="$t('table.courseware.transStatus')" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.row.transType == 1 ? '处理中' : scope.row.transType == 2 ? '成功' : scope.row.transType == 3 ? '失败' : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="state == 'u'" prop="sort" label="排序值" width="200" show-overflow-tooltip />
      <el-table-column
        :label="$t('table.actions')"
        fixed="right"
        align="center"
        width="80"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button v-if="state == 'c'" type="text" size="mini" @click="handleselect(scope.row)">选择</el-button>
          <el-button v-if="state == 'u' && $route.query.status != '0'" type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="state == 'u' && $route.query.status != '0'" type="text" size="mini" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 修改界面 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      center
      width="800px"
      top="25vh"
    >
      <el-form
        ref="dataForm"
        :model="dialogSearchInsert"
        status-icon
        label-width="80px"
        label-position="left"
        :rules="rules"
      >
        <el-form-item label="课件名称" prop="name">
          <el-input
            v-model="dialogSearchInsert.name"
            placeholder="请输入课件名称"
          />
        </el-form-item>
        <el-form-item label="排序值" prop="sort">
          <el-input
            v-model="dialogSearchInsert.sort"
            placeholder="请输入排序值"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="dialogFormVisible = false"
        >取消</el-button>
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="updateData()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { specialText } from '@/utils/validate'
// import {
//   courseWareNotLinkQueryList,
//   courseWareLinkQueryList,
//   courseWareInsert,
//   courseWareUpdate,
//   courseWareDel
// } from '@/api/hundredLearning/index'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getToken } from '@/utils/auth'

export default {
  name: 'PunchClockCourseware',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: '',
        id: '-1'
      },
      temp: {
        name: '',
        remark: '',
        super_id: this.superId,
        layers: '1',
        videoType: '5'
      },
      dialogFormVisible: false,
      dialogSearchInsert: {
        id: '',
        name: '',
        sort: ''
      },
      dialogStatus: '',
      textMap: {
        update: '设置',
        create: '新建课件分类'
      },
      dialogUploadVisible: false,
      rules: {
        name: [
          { required: true, message: '请输入课件分类名称', trigger: 'change' },
          { validator: specialText, trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      multipleSelection: [],
      uploadaction: '/API-COURSE/admin/courseVideo/uploadVideo',
      uploadHeaders: { 'ttsxAuthToken': getToken() },
      uplaodLimit: 4,
      superId: '-1',
      parentId: [],
      uploadNum: 0,
      uploadLoading: false,
      moveIds: '',
      moveSuperId: '',
      moveDialogVisible: false,
      moveLoading: false,
      movefilterText: '',
      moveTreeData: [],
      moveClickTree: [],
      movedefaultProps: {
        children: 'list',
        label: 'name'
      },
      fileList: [],
      courseId: '',
      state: ''
    }
  },
  watch: {
    movefilterText(val) {
      this.$refs.movetree.filter(val)
    }
  },
  created() {
    this.courseId = this.$route.query.courseId || ''
    this.state = this.$route.query.type || ''
    // this.getList()
  },
  methods: {
    handleRefresh() {
      this.getList()
    },
    rowClass({ row, rowIndex }) {
      return {
        padding: '5px 0',
        height: '20px',
        background: 'rgba(247,247,248,1)'
      }
    },
    getList(obj) {
      this.listLoading = true
      if (this.state == 'c') {
        var query = {
          page: obj ? obj.page : this.listQuery.page,
          pageSize: obj ? obj.limit : this.listQuery.limit,
          courseId: this.courseId,
          id: this.listQuery.id
        }
        return new Promise((resolve, reject) => {
          courseWareNotLinkQueryList(query).then(response => {
            this.list = response.data.data.rows
            this.total = response.data.data.total
            this.listLoading = false
          }).catch(error => {
            this.listLoading = false
            reject(error)
          })
        })
      } else {
        var query = {
          page: obj ? obj.page : this.listQuery.page,
          pageSize: obj ? obj.limit : this.listQuery.limit,
          name: this.listQuery.name,
          courseId: this.courseId
        }
        return new Promise((resolve, reject) => {
          courseWareLinkQueryList(query).then(response => {
            this.list = response.data.data.rows
            console.log(this.list)
            this.total = response.data.data.total
            this.listLoading = false
          }).catch(error => {
            this.listLoading = false
            reject(error)
          })
        })
      }
    },

    handleselect(row) {
      this.selectItem(row.id)
    },
    handleSelects() {
      const arr = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })
        var ids = arr.join(',')
        this.selectItem(ids)
      } else {
        this.$message({
          message: '请选择需要选择的数据！',
          type: 'warning'
        })
      }
    },
    selectItem(ids) {
      this.$confirm('此操作将为课程选择课件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          courseWareInsert({ courseId: this.courseId, videoIds: ids }).then(() => {
            this.$notify({
              title: '成功',
              message: '选择成功',
              type: 'success',
              duration: 2000
            })
            this.$router.push({ path: this.$filterPath('course') })
          }).catch(error => {
            reject(error)
          })
        })
      }).catch((e) => {
        this.$message({
          type: 'info',
          message: e.msg || '已取消选择'
        })
      })
    },
    goback() {
      this.listQuery.name = ''
      if (this.superId !== 1) {
        this.superId = this.parentId[this.parentId.length - 1]
        this.parentId.splice(this.parentId.length - 1, 1)
        this.listQuery.id = this.superId
        this.getList()
      } else {
        this.listQuery.id = '-1'
        this.getList()
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resettingBtn() {
      this.listQuery.name = ''
      this.listQuery.page = 1
      this.getList()
    },
    handleUpdate(row) {
      this.dialogSearchInsert = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.dialogSearchInsert)
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.1)'
          })
          return new Promise((resolve, reject) => {
            courseWareUpdate(tempData).then(() => {
              loading.close()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        }
      })
    },
    handleDel(row) {
      this.deleteItem(row.id)
    },
    handleDeletes() {
      const arr = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })
        const ids = arr.join(',')
        this.deleteItem(ids)
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'error'
        })
      }
    },
    deleteItem(ids) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          courseWareDel({ ids: ids }).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.listQuery.page = 1
            this.getList()
          }).catch(error => {
            reject(error)
          })
        })
      }).catch((e) => {
        this.$message({
          type: 'info',
          message: e.msg || '已取消删除'
        })
      })
    },
    handleLevel(row) {
      this.parentId.push(row.super_id)
      this.superId = row.id
      this.listQuery.id = row.id
      this.getList({ page: 1, limit: 10 })
    },
    handleDownload() {
      // this.downloadLoading = true
      //   import('@/vendor/Export2Excel').then(excel => {
      //     const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
      //     const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
      //     const data = this.formatJson(filterVal, this.list)
      //     excel.export_json_to_excel({
      //       header: tHeader,
      //       data,
      //       filename: 'table-list'
      //     })
      //     this.downloadLoading = false
      //   })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    },
    handleMove() {
      const arr = []
      this.movefilterText = ''
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })
        this.moveIds = arr.join(',')
        this.handleSelQy()
      } else {
        this.$message({
          message: '请选择需要移动的数据！',
          type: 'error'
        })
      }
    },

    qyfilterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    checkTreeData(a, b) {
      if (b.checkedKeys.length > 0) {
        this.$refs.movetree.setCheckedKeys([a.id])
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss">
  $dark_gray: #bfced6;
  .courseware-container {
    .courseware-search {
      background-color: #fff;
      padding: 0 20px;
      .svg-container {
        padding: 0;
        color: $dark_gray;
        vertical-align: middle;
        display: inline-block;
        &_login {
          font-size: 20px;
        }
      }
      .search-input {
        width: 60%;
        position: relative;
        &:after {
          content: "";
          position: absolute;
          left: -25px;
          right: 0;
          bottom: 8px;
          height: 1px;
          background: rgba(226, 227, 232, 1);
        }
        input {
          outline: none;
          background: transparent;
          border: none;
          outline: medium;
          padding: 0;
          &:focus {
            outline: none;
            background-color: transparent;
          }
        }
      }
      .courseware-search-btn {
        display: inline-block;
        float: right;
      }
      &.merge {
        height: 50px;
        line-height: 50px;
      }
    }
    .btn-container {
      display: flex;
      height: 36px;
      line-height: 36px;
      margin-top: 20px;
      margin-bottom: 20px;
      .btn-container-title {
        flex: 1;
        font-size: 16px;
        font-weight: bold;
        font-family: PingFangSC-Medium;
        color: rgba(51, 51, 51, 1);
      }
    }
    .el-upload-dragger {
      width: 400px;
    }
    .demo-table-expand .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: 45%;
      display: inline-block;
      vertical-align: top;
    }
    .el-upload-list__item .el-progress__text{
      bottom: -13px;
      top: auto;
    }
  }
</style>

